package org.example;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 用于记录每月累计收入的类
 */
public class MonthlyEarningsRecorder {
    static final Logger logger = LoggerFactory.getLogger(MonthlyEarningsRecorder.class);
    private static final String FILE_PATH = "src/main/resources/config/earning.properties";
    
    public static void saveEarnings(String month, double earnings) {
        File configDir = new File("src/main/resources/config");
        if (!configDir.exists()) {
            configDir.mkdirs();
            logger.info("Create configuration directory:" + configDir.getAbsolutePath());
        }
        
        Properties props = new Properties();
        try (InputStream input = Files.newInputStream(Paths.get(FILE_PATH))) {
            props.load(input);
        } catch (IOException e) {
            logger.error("The configuration file does not exist, a new file will be created");
        }
        
        if (!props.containsKey(month)) {
            props.setProperty(month, "0.0");
            logger.info("New month record:" + month);
        }
        
        props.setProperty(month, String.valueOf(earnings));
        
        try (OutputStream output = Files.newOutputStream(Paths.get(FILE_PATH))) {
            props.store(output, "Monthly Earnings");
            logger.info("Successfully saved " + month + " income record: " + earnings);
        } catch (IOException e) {
            logger.error("Failed to save accumulated income: " + e.getMessage());
        }
    }

    public static double getEarnings(String month) {
        Properties props = new Properties();
        try (InputStream input = Files.newInputStream(Paths.get(FILE_PATH))) {
            props.load(input);
            String earnings = props.getProperty(month);
            if (earnings != null) {
                logger.info("Successfully read income records for " + month + " : " + earnings);
                return Double.parseDouble(earnings);
            }
        } catch (IOException e) {
            logger.error("Failed to read cumulative income: " + e.getMessage());
        }
        logger.error("The income record for " + month + " does not exist, return the default value of 0.0");
        return 0.0;
    }

    public static void saveCustomEarnings(String month, double earnings) {
        saveEarnings(month, earnings);
    }
}